/**
 * 受保护的路由组件
 * 用于验证用户登录状态并处理重定向逻辑
 * 
 * 功能说明：
 * - 检查用户是否已登录
 * - 未登录用户重定向到登录页面
 * - 支持权限验证
 * - 自动恢复登录状态
 * 
 * @author 项目开发团队
 * @version 1.0.0
 */

import React, { useEffect } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { Navigate, useLocation } from 'react-router-dom'
import { SpinLoading } from 'antd-mobile'
import { verifyAuth, selectIsAuthenticated, selectAuthLoading } from '../store/slices/authSlice'

/**
 * 受保护的路由组件
 * @param {Object} props - 组件属性
 * @param {React.ReactNode} props.children - 子组件
 * @param {Array} props.requiredPermissions - 需要的权限列表
 * @param {string} props.fallbackPath - 权限不足时的重定向路径
 * @returns {JSX.Element} 受保护的路由组件
 */
const ProtectedRoute = ({ 
  children, 
  requiredPermissions = [], 
  fallbackPath = '/login' 
}) => {
  const dispatch = useDispatch()
  const location = useLocation()
  
  // 从Redux获取认证状态
  const isAuthenticated = useSelector(selectIsAuthenticated)
  const isLoading = useSelector(selectAuthLoading)
  const permissions = useSelector(state => state.auth.permissions)
  
  // 组件挂载时验证登录状态
  useEffect(() => {
    if (!isAuthenticated && !isLoading) {
      dispatch(verifyAuth())
    }
  }, [dispatch, isAuthenticated, isLoading])
  
  // 显示加载状态
  if (isLoading) {
    return (
      <div style={{
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        height: '100vh',
        flexDirection: 'column',
        gap: '16px'
      }}>
        <SpinLoading color='primary' />
        <div style={{ color: '#666', fontSize: '14px' }}>验证登录状态中...</div>
      </div>
    )
  }
  
  // 未登录，重定向到登录页面
  if (!isAuthenticated) {
    return (
      <Navigate 
        to={fallbackPath} 
        state={{ from: location }} 
        replace 
      />
    )
  }
  
  // 检查权限
  if (requiredPermissions.length > 0) {
    const hasPermission = requiredPermissions.some(permission => 
      permissions.includes(permission) || permissions.includes('admin')
    )
    
    if (!hasPermission) {
      return (
        <Navigate 
          to="/unauthorized" 
          state={{ from: location }} 
          replace 
        />
      )
    }
  }
  
  // 已登录且有权限，渲染子组件
  return <>{children}</>
}

export default ProtectedRoute
